import { Component,ChangeDetectorRef } from '@angular/core';
import { NavController, LoadingController } from 'ionic-angular';
import { PhotoLibrary } from '@ionic-native/photo-library';
import { OthersPage } from './others/others';

@Component({
  selector: 'page-production',
  templateUrl: 'production.html'
})
export class ProductionPage {
  private pictures = [];

  constructor(public navCtrl: NavController,
              private photoLibrary: PhotoLibrary,
              public loadingCtrl: LoadingController,
              private ref: ChangeDetectorRef) {

    this.showLoading('loading...')
    this.getPicturesFromLocal();
    ref.detach();
    setInterval(() => {
      this.ref.detectChanges();
    }, 1000);
  
  }

  ionViewDidEnter(){
    this.getPicturesFromLocal()
  }



  doRefresh(refresher) {
      this.getPicturesFromLocal(refresher)
      setTimeout(()=>{
        refresher.complete();
      },1000)
   }

  getPicturesFromLocal(refresher?){
    var that = this;
    this.photoLibrary.requestAuthorization().then(() => {
      this.photoLibrary.getLibrary({includeAlbumData: true}).subscribe({
        next: library => {
          var id: any;
          var arr = [];
          this.photoLibrary.getAlbums().then(
            result => result.forEach(function(result){
              if(result.title == "caihui"){
                id= result.id;
                console.log(id);
                library.forEach(function(libraryItem) {
                  if(libraryItem.albumIds[0] == id){
                    arr.push(libraryItem.photoURL);
                  }
                });
              }
            }));
          that.pictures = arr;
          // refresher.complete();
        that.hideLoading();
        },
        error: err => { console.log('could not get photos'); },
        complete: () => { console.log('done getting photos'); }
      });
    })
    .catch(err => console.log('permissions weren\'t granted'));
  }

      /**
   * 统一调用此方法显示loading
   * @param content 显示的内容
   */
  private loadingIsOpen:any;
  private loading:any;
  showLoading(content: string = ''): void {
    if (!this.loadingIsOpen) {
      this.loadingIsOpen = true;
      this.loading = this.loadingCtrl.create({
          content: content
      });
      this.loading.present();
      setTimeout(() => { //最长显示2秒
          this.loadingIsOpen && this.loading.dismiss();
          this.loadingIsOpen = false;
      }, 2000);
    }
  };

  /**
  * 关闭loading
  */
  hideLoading(): void {
    this.loadingIsOpen && this.loading.dismiss();
    this.loadingIsOpen = false;
  }


  openOthers(): void{
      this.navCtrl.push(OthersPage);
  }

}
